package com.songcha.module_main.ui.activity.main

import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.songcha.library_base.base.BaseFragment
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.event.home.BookClickEvent
import com.songcha.library_business.handler.home_dialog.AbsHomeDialog
import com.songcha.library_business.handler.home_dialog.AppUpdateDialog
import com.songcha.library_business.handler.home_dialog.CurrentTimeErrorDialog
import com.songcha.library_business.handler.home_dialog.NoNetWorkDialog
import com.songcha.library_business.handler.home_dialog.SqueezeAccountLoginDialog
import com.songcha.library_business.proxy.main.HideBottomNavigationEvent
import com.songcha.library_business.proxy.main.ToHomeEvent
import com.songcha.library_business.proxy.main.ToMyBookShelfEvent
import com.songcha.library_business.ui.view.BookOpenView
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_business.util.MajiaBaoUtil
import com.songcha.library_common.handler.AppExitTipHandler
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.BottomNavigationItemView
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.ui.view.MsgTipsView
import com.songcha.library_common.util.ColorUtil
import com.songcha.module_main.R
import com.songcha.module_main.databinding.MainActivityMainBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


@Route(path="/main/MainActivity")
class MainActivity : BaseMvvmActivity<MainViewModel, MainActivityMainBinding>(),BottomNavigationView.IOnBottomNavigationItemChangeListener,BookOpenView.IOnBookAnimationListener {
    //private lateinit var binding: AppActivityMainBinding
    /*companion object{
        private var mBottomNavigationCurrentTag = ""

        @JvmStatic
        fun getBottomNavigationCurrentTag():String{
            return mBottomNavigationCurrentTag
        }
    }*/


    val mFragments= mutableListOf<BaseFragment>(

    )

    override fun getLayoutId(): Int {
        return R.layout.main_activity_main
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if(savedInstanceState != null){
            //TODO
            BusinessJumpUtil.toSplashActivity(this)
            finish()
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        val majiaName = MajiaBaoUtil.getMajiaName()

        if(majiaName == "douyue"){
            mFragments.add(ARouter.getInstance().build("/home/HomeFragment").navigation() as BaseFragment)
        }else{
            if(FunctionConfig.IS_CATEGORY_ENABLED)
                mFragments.add(ARouter.getInstance().build("/category/CategoryFragment").navigation() as BaseFragment)
        }
        mFragments.add(ARouter.getInstance().build("/task/TaskFragment").navigation() as BaseFragment)
        if(majiaName == "douyue"){
            if(FunctionConfig.IS_CATEGORY_ENABLED)
                mFragments.add(ARouter.getInstance().build("/category/CategoryFragment").navigation() as BaseFragment)
        }else{
            mFragments.add(ARouter.getInstance().build("/home/HomeFragment").navigation() as BaseFragment)
        }
        mFragments.add(ARouter.getInstance().build("/bookshelf/BookShelfFragment").navigation() as BaseFragment)
        mFragments.add(ARouter.getInstance().build("/mine/MineFragment").navigation() as BaseFragment)

        intent?.let {
            val isExit=it.getBooleanExtra("is_exit",false)
            if(isExit)
                finish()
        }

        val vp=databinding.mainNsvp
        vp.adapter=object: FragmentStatePagerAdapter(supportFragmentManager){
            override fun getCount(): Int {
                return mFragments.size
            }

            override fun getItem(position: Int): Fragment {
                return mFragments[position]
            }

        }

        val bnvItemList= mutableListOf<BottomNavigationItemView>()

        fun addHomeTab(title: String,iconNormalResId:Int,iconSelectedResId:Int){
            val bnvItemHome = BottomNavigationItemView(this){p,b,v->
                return@BottomNavigationItemView getBottomTabView(p,b,v,title,iconNormalResId,iconSelectedResId)
            }
            bnvItemHome.layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            bnvItemList.add(bnvItemHome)
        }

        fun addCateTab(title: String,iconNormalResId:Int,iconSelectedResId:Int){
            val bnvItemCategory= BottomNavigationItemView(this){p,b,v->
                return@BottomNavigationItemView getBottomTabView(p,b,v,title,iconNormalResId,iconSelectedResId)
            }
            bnvItemCategory.layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
            bnvItemList.add(bnvItemCategory)
        }

        if(majiaName == "douyue"){
            addHomeTab("首页",R.mipmap.main_icon_home_normal,R.mipmap.main_icon_home_selected)
        }else{
            addCateTab("首页",R.mipmap.main_icon_category_normal,R.mipmap.main_icon_category_selected)
        }

        val bnvItemTask = BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"任务",R.mipmap.main_icon_task_normal,R.mipmap.main_icon_task_selected)
        }
        bnvItemTask.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemTask)

        if(majiaName == "douyue"){
            addCateTab("分类",R.mipmap.main_icon_category_normal,R.mipmap.main_icon_category_selected)
        }else{
            addHomeTab("分类",R.mipmap.main_icon_home_normal,R.mipmap.main_icon_home_selected)
        }

        val bnvItemBookshelf = BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"书架",R.mipmap.main_icon_shelf_normal,R.mipmap.main_icon_shelf_selected)
        }
        bnvItemBookshelf.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemBookshelf)

        val bnvItemMine = BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"我的",R.mipmap.main_icon_mine_normal,R.mipmap.main_icon_mine_selected)
        }
        bnvItemMine.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemMine)

        //TODO
        /*val selectTitleColor = ColorUtil.getResourceColor(this, com.songcha.library_common.R.color.primary)

        fun addHomeTab(title:String){
           val bnvItemHome=BottomNavigationItemView(this)
           bnvItemHome.layoutParams=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
           bnvItemHome.setIcon(17f.dp2px(),R.mipmap.main_icon_home_normal,R.mipmap.main_icon_home_selected)
           bnvItemHome.setTitle(title,13f.sp2px(),Color.BLACK,13f.sp2px(),selectTitleColor)
           bnvItemList.add(bnvItemHome)
       }

       fun addCateTab(title:String){
           if(FunctionConfig.IS_CATEGORY_ENABLED){
               val bnvItemCategory=BottomNavigationItemView(this)
               bnvItemCategory.layoutParams=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
               bnvItemCategory.setIcon(17f.dp2px(),R.mipmap.main_icon_category_normal,R.mipmap.main_icon_category_selected)
               bnvItemCategory.setTitle(title,13f.sp2px(),Color.BLACK,13f.sp2px(),selectTitleColor)
               bnvItemList.add(bnvItemCategory)
           }
       }

       if(majiaName == "douyue"){
           addHomeTab("首页")
       }else{
           addCateTab("首页")
       }

       val bnvItemTask=BottomNavigationItemView(this)
       bnvItemTask.layoutParams=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
       bnvItemTask.setIcon(17f.dp2px(),R.mipmap.main_icon_task_normal,R.mipmap.main_icon_task_selected)
       bnvItemTask.setTitle("任务",13f.sp2px(),Color.BLACK,13f.sp2px(),selectTitleColor)
       bnvItemList.add(bnvItemTask)

       if(majiaName == "douyue"){
           addCateTab("分类")
       }else{
           addHomeTab("分类")
       }

       val bnvItemMine=BottomNavigationItemView(this)
       bnvItemMine.layoutParams=LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)
       bnvItemMine.setIcon(17f.dp2px(),R.mipmap.main_icon_mine_normal,R.mipmap.main_icon_mine_selected)
       bnvItemMine.setTitle("我的",13f.sp2px(),Color.BLACK,13f.sp2px(),selectTitleColor)
       bnvItemList.add(bnvItemMine)*/


        //TODO

        for(i in 0 until mFragments.size){
            val frag=mFragments[i]
            val bnvItem = bnvItemList[i]
            bnvItem.TAG=frag.TAG
            databinding.mainBnv.addView(bnvItem)
        }

        databinding.mainBnv.setOnBottomNavigationItemChangeListener(this)
        databinding.mainBnv.setViewPager(vp)
        databinding.mainBov.setOnBookAnimationListener(this)

        //use responsibility link mode to handle home dialog gracefully
        val dialogs= mutableListOf<AbsHomeDialog>()
        dialogs.add(AppUpdateDialog(this))
        dialogs.add(CurrentTimeErrorDialog(this))
        dialogs.add(NoNetWorkDialog(this))
        dialogs.add(SqueezeAccountLoginDialog(this))
        dialogs.sortBy { it.getPriority()*-1 }
        for(i in 0 until dialogs.size-1){
            dialogs[i].setNextDialog(dialogs[i+1])
        }
        dialogs[0].handleShowDialog()

        EventBus.getDefault().register(this)

    }

    private fun getBottomTabView(p:LinearLayout,isSelect:Boolean,v: View?,title:String,
                                 iconNormalResId:Int,iconSelectedResId:Int):View{
        if(v == null){
            val tab = LayoutInflater.from(p.context).inflate(R.layout.main_bottom_tab_item,p,false)
            val tvTitle = tab.findViewById<TextView>(R.id.main_tv_title)
            val ivIcon = tab.findViewById<ImageView>(R.id.main_iv_icon)
            tvTitle.text = title
            val mtv = tab.findViewById<MsgTipsView>(R.id.main_mtv)
            ivIcon.setImageResource(iconNormalResId)
            val hasSelect = SharedPreferenceHelper.getBoolean("bottom_tab","click_task")
            ViewHelper.setVisibility(title == "任务" && !hasSelect,mtv)
            return tab
        }else{
            val tab = v!! as FrameLayout
            val tvTitle = tab.findViewById<TextView>(R.id.main_tv_title)
            val ivIcon = tab.findViewById<ImageView>(R.id.main_iv_icon)
            val mtv = tab.findViewById<MsgTipsView>(R.id.main_mtv)
            if(isSelect){
                val selectTitleColor = ColorUtil.getResourceColor(this, com.songcha.library_common.R.color.primary)
                tvTitle.setTextColor(selectTitleColor)
                ivIcon.setImageResource(iconSelectedResId)
                ViewHelper.setVisibility(false,mtv)
                if(title == "任务")
                    SharedPreferenceHelper.setBoolean("bottom_tab","click_task",true)
            }else{
                //ccl.setContainerBackgroundColor(Color.WHITE)
                //tvTitle.setTextColor(Color.BLACK)
                tvTitle.setTextColor(Color.BLACK)
                ivIcon.setImageResource(iconNormalResId)
                val hasSelect = SharedPreferenceHelper.getBoolean("bottom_tab","click_task")
                ViewHelper.setVisibility(title == "任务" && !hasSelect,mtv)
            }
            return v!!
        }
    }

    /**
     * exit app by indirect way
     */
    /*override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        finish()
    }*/

    @Subscribe
    fun onToMyBookShelf(event:ToMyBookShelfEvent){
        databinding.mainBnv.select(3)
    }

    @Subscribe
    fun onToHome(event:ToHomeEvent){
        databinding.mainBnv.select(0)
    }

    @Subscribe
    fun onHideBottomNavigation(event:HideBottomNavigationEvent){
        if(event.isHide){
            databinding.mainCclBnv.visibility=View.GONE
        }else{
            databinding.mainCclBnv.visibility=View.VISIBLE
        }
    }

    @Subscribe
    fun onBookClickEvent(event: BookClickEvent){
        val arr=IntArray(2)
        event.img.getLocationInWindow(arr)
        databinding.mainBov.startBookOpenAnimation(event.bookId,event.img,arr[0],arr[1])
    }

    override fun onBottomNavigationItemChange(position: Int,tag:String) {
        for(frag in mFragments){
            if(frag is BottomNavigationView.IOnBottomNavigationItemChangeListener)
                frag.onBottomNavigationItemChange(position,tag)
        }

    }

    /*override fun onApplyWindowInsetsCall(v: View, insets: WindowInsetsCompat) {
        for(item in mFragments){
            (item as IOnApplyWindowInsetsCall).onApplyWindowInsetsCall(v,insets)
        }
    }*/

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        return AppExitTipHandler.handleOnKeyUp(this,keyCode){
            super.onKeyUp(keyCode, event)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onBookOpenAnimationEnd(bookId: String) {
        BusinessJumpUtil.toBookDetail(bookId)
        //close startActivity anim
        //overridePendingTransition(0,0)
    }

    override fun onBookCloseAnimationEnd(bookId: String) {

    }

    override fun onResume() {
        super.onResume()
        databinding.mainBov.startBookCloseAnimation()
    }
}